package com.bnq.logc.ui.file

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.bnq.logc.R

class WebViewFragment : Fragment() {

    private var onBack:((WebViewFragment)->Unit)? = null

    fun setOnBack(onBack:(WebViewFragment)->Unit){
        this.onBack = onBack
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_web_view,container,false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val tvTitle = view.findViewById<TextView>(R.id.title)
        val webView = view.findViewById<WebView>(R.id.web_view)
        view.findViewById<View>(R.id.back).setOnClickListener {
            onBack?.invoke(this)
        }

        webView.settings.apply {
            allowFileAccess = true
            allowContentAccess = true
            allowFileAccessFromFileURLs = true
            allowUniversalAccessFromFileURLs = true
            useWideViewPort = true
            loadWithOverviewMode = true
            setSupportZoom(true)
            builtInZoomControls = true
            displayZoomControls = false
            loadsImagesAutomatically = true
            blockNetworkImage = false
            blockNetworkLoads = false
        }

        webView.webChromeClient = object : android.webkit.WebChromeClient() {

            override fun onReceivedTitle(view: WebView?, title: String?) {
                super.onReceivedTitle(view, title)
                view?.post {
                    tvTitle.text = title
                }
            }
        }

        arguments?.getString("url")?.let {
            webView.loadUrl(it)
        }
    }

}